package com.irdstudio.apicenter.gateway.web.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;

import com.gexin.rp.sdk.base.IPushResult;
import com.irdstudio.apicenter.gateway.comm.MaccsPacket;
import com.irdstudio.apicenter.gateway.comm.MaccsPacketUtil;
import com.irdstudio.apicenter.gateway.core.dm.AppChannelAccess;
import com.irdstudio.apicenter.gateway.core.dm.AppDeviceRegister;
import com.irdstudio.apicenter.gateway.core.dm.AppPushTask;
import com.irdstudio.apicenter.gateway.core.jdbc.MaccsBaseDAO;
import com.irdstudio.apicenter.gateway.util.date.CurrentDateUtil;
import com.irdstudio.apicenter.gateway.util.pub.KeyUtil;
import com.irdstudio.apicenter.gateway.util.push.PushCfg;
import com.irdstudio.apicenter.gateway.util.push.PushUtils;
import com.irdstudio.apicenter.gateway.util.spring.BeanUtils;
import com.irdstudio.apicenter.gateway.web.MaccsException;
import com.irdstudio.apicenter.gateway.web.MaccsTradeDefineVo;
import com.irdstudio.apicenter.gateway.web.view.JsonView;
import com.irdstudio.apicenter.gateway.web.view.View;

/**
 * 消息推送交易(单个设备、单条通知）
 * 
 * @author ZhangHao
 * @since 1.0
 * @date 2015.8.25
 *
 */
@Controller
public class AppPushSingleMsg implements IController {

	@Override
	public View execute(MaccsTradeDefineVo tradeDefine, MaccsPacket inPacket,
			HttpServletRequest request, HttpServletResponse response)
			throws MaccsException {

		MaccsPacket maccsPacket = null;
		try {

			AppPushTask task = this.pushMessageToSingle(inPacket);
			if(null!=task){
			    maccsPacket = MaccsPacketUtil.makeSimpleSuccessPacket(task
	                    .getTaskId());
			}
		} catch (Exception e) {
			logger.error("appPushMsgToSingleController error ", e);
			maccsPacket = MaccsPacketUtil.makeFailurePacket(e.getMessage());
		}
		return new JsonView(request, response, maccsPacket);
	}

	/**
	 * 判断并执行推送
	 * @param inPacket
	 * @return
	 * @throws MaccsException
	 */
	public AppPushTask pushMessageToSingle(MaccsPacket inPacket)
			throws MaccsException {
		try {

			// 获取请求端传递的数据
			String userId = inPacket.getValue("user_id");
			String appId = inPacket.getValue("app_id");
			String pushAlterMsg = StringEscapeUtils.unescapeJava(inPacket.getValue("push_alter_msg"));
			String pushParams = StringEscapeUtils.unescapeJava(inPacket.getValue("push_params"));
//			String pushAlterMsg = StringUtil.decodeUnicode(inPacket.getValue("push_alter_msg"));
//			String pushParams = StringUtil.decodeUnicode(inPacket.getValue("push_params"));
			String pkValue = inPacket.getValue("pk_value");
//			String pushType = StringUtil.decodeUnicode(inPacket.getValue("push_type"));
			String pushType = StringEscapeUtils.unescapeJava(inPacket.getValue("push_type"));
			Integer iosBadge = inPacket.getIntValue("ios_badge");

			MaccsBaseDAO dao = BeanUtils.getBean(MaccsBaseDAO.class);

			// 如果消息已经在推送任务表中,则不再推送
			int c = dao.findForInt(sql1, new Object[] { appId, pkValue });
			if (c >= 1)
				return null;

			// 获取APP对应的推送配置信息
			AppChannelAccess access = dao.findBean(AppChannelAccess.class,
					new Object[] { appId });
			Validate.notNull(access, "appChannelAccess is null . appid:{0}",
					new Object[] { appId });

			String pushAppId = access.getPushAppId();
			String pushUrl = access.getPushUrl();
			String pushAppKey = access.getPushAppKey();
			String pushMasterSecret = access.getPushMasterSecret();
			PushCfg pushCfg = new PushCfg(appId, pushAppId, pushUrl,
					pushAppKey, pushMasterSecret);

			// 获取user登记的设备信息
			List<AppDeviceRegister> deviceRegisters = dao.findBeanList(sql,
					AppDeviceRegister.class,
					new Object[] { appId, userId, "Y" });
			Validate.notNull(deviceRegisters,
					"deviceRegister is null . userId:{0}",
					new Object[] { userId });
			AppDeviceRegister deviceRegister = deviceRegisters.get(0);
			String deviceId = deviceRegister.getPushDeviceId();
			String deviceType = deviceRegister.getDeviceType();

			List<String> deviceids = new ArrayList<String>();
			deviceids.add(deviceId);

			// 推送消息
			IPushResult result = PushUtils.pushMessage(pushCfg, deviceType,
					pushType, pushAlterMsg, pushParams, deviceids, iosBadge);

			// 存储推送信息
			Map<String, Object> response = result.getResponse();
			AppPushTask pushTask = new AppPushTask();
			pushTask.setAppId(appId);
			pushTask.setDeviceId(deviceId);
			pushTask.setPkId(KeyUtil.createUniqueKey());
			pushTask.setPkValue(pkValue);
			pushTask.setPushAlterMsg(pushAlterMsg);
			pushTask.setPushAppId(pushAppId);
			pushTask.setPushAppKey(pushAppKey);
			pushTask.setPushMasterSecret(pushMasterSecret);
			pushTask.setPushParams(pushParams);
			pushTask.setPushRsMsg(response.toString());
			pushTask.setPushStatus(MapUtils.getString(response, "result"));
			pushTask.setPushTime(CurrentDateUtil.getTodayDateEx());
			pushTask.setPushType(pushType);
			pushTask.setPushUrl(pushUrl);
			pushTask.setTaskId(MapUtils.getString(response, "contentId"));
			pushTask.setUserId(userId);

			Validate.isTrue(dao.insertBean(pushTask) > 0,
					"insert pushTask error.");

			return pushTask;

		} catch (Exception e) {
			logger.error("pushMessageToSingle error ", e);
			throw new MaccsException(e);
		}
	}

	private final static Logger logger = LoggerFactory
			.getLogger(AppPushSingleMsg.class);

	private final String sql = "select * from app_device_register where app_id = ? and app_userid = ? and is_allow = ?";
	private final String sql1 = "select count(1) from app_push_task where app_id = ? and pk_value = ? ";
	
}